package com.dotools.umlibrary

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.umeng.commonsdk.utils.UMUtils
import com.umeng.message.PushAgent
import com.umeng.message.api.UPushRegisterCallback
import com.umeng.umcrash.UMCrash
import com.umeng.union.UMUnionSdk
import com.umeng.union.api.UMUnionApi


object UMPostUtils {
    private val tag: String = "MobclickAgent"
    private var debugLog: Boolean = false
    private var callback: Callback? = null
    private val sAdCallback: UMUnionApi.AdCallback = object : UMUnionApi.AdCallback() {
        override fun onShow(p0: UMUnionApi.AdType) {
            Log.i("UPush", "onShow")
            callback?.show(p0.name)
        }

        override fun onClicked(p0: UMUnionApi.AdType) {
            Log.i("UPush", "onClicked")
            callback?.clicked(p0.name)
        }

        override fun onFailure(p0: UMUnionApi.AdType, p1: String) {
            super.onFailure(p0, p1)
            Log.i("UPush", "onFailure:$p1")
            callback?.onFailure(p0.name, p1)
        }
    }

    interface Callback {
        fun show(name: String)
        fun clicked(name: String)
        fun onFailure(name: String, msg: String)
    }

    fun getDeviceToken(context: Context): String? {
        return PushAgent.getInstance(context).registrationId
    }


    fun prePushInit(application: Context, appkey: String, secret: String) {
        PushAgent.setup(application, appkey, secret)
    }

    fun preInit(application: Context, appkey: String, channel: String) {
        UMConfigure.preInit(application, appkey, channel)
    }

    /**
     * 初始化common库 模式手动采集
     * 参数1:上下文，不能为空
     * 参数2:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
     * 参数3:Push推送业务的secret没有传null
     */
    fun init(application: Context) {
        UMConfigure.init(application, UMConfigure.DEVICE_TYPE_PHONE, null)
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL)
        UMConfigure.setProcessEvent(true)//支持多进程打点
        UMConfigure.getOaid(application) { oaid -> Log.e("UPush", "oaid=$oaid") }
    }

    fun init(application: Context, appkey: String, channel: String) {
        UMConfigure.init(application, appkey, channel, UMConfigure.DEVICE_TYPE_PHONE, null)
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL)
        UMConfigure.setProcessEvent(true)//支持多进程打点
    }


    /**
     * 初始化common库 模式为自动采集
     * 参数1:上下文，不能为空
     * 参数2:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
     * 参数3:Push推送业务的secret没有传null
     */
    fun initAuto(application: Context) {
        UMConfigure.init(application, UMConfigure.DEVICE_TYPE_PHONE, null)
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
        UMConfigure.setProcessEvent(true)//支持多进程打点
    }


    /**
     * 设置用户是否同意了隐私权限
     */
    fun submitPolicyGrant(application: Context, b: Boolean) {
        UMConfigure.submitPolicyGrantResult(application, b)
    }


    fun initPush(application: Context) {
        val isMainProcess = UMUtils.isMainProgress(application)
        if (isMainProcess) {
            //启动优化：建议在子线程中执行初始化
            Thread { createPush(application) }.start()
        } else {
            //若不是主进程（":channel"结尾的进程），直接初始化sdk，不可在子线程中执行
            createPush(application)
        }
    }

    //在App的SplashActivity或MainActivity中onCreate()方法添加
    fun pushAppStart(context: Context) {
        PushAgent.getInstance(context).onAppStart()
    }

    private fun createPush(application: Context) {
        //获取消息推送实例
        val pushAgent = PushAgent.getInstance(application)
        //注册推送服务，每次调用register方法都会回调该接口
        pushAgent.register(object : UPushRegisterCallback {
            override fun onSuccess(token: String) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.i("UPush", "注册成功 deviceToken:$token")
                initUpushCallBack(application)
            }

            override fun onFailure(errCode: String, errDesc: String) {
                Log.e("UPush", "注册失败 code:$errCode, desc:$errDesc")
            }
        })

    }
    private fun initUpushCallBack(context: Context){
        setCallback(object : Callback {
            override fun show(name: String) {
                val map = HashMap<String, String>()
                map["TYPE"] = name
                onEventMap(context.applicationContext, "upush_show", map)
                if(name=="BANNER"){
                    setUpushBannerTime(context.applicationContext,System.currentTimeMillis()/1000)
                }else{
                    setUpushNotificationTime(context.applicationContext,System.currentTimeMillis()/1000)
                }
            }

            override fun clicked(name: String) {
                val map = HashMap<String, String>()
                map["TYPE"] = name
                onEventMap(context.applicationContext, "upush_clicked", map)
            }

            override fun onFailure(name: String, msg: String) {
                val map = HashMap<String, String>()
                map["error"] = "$name-$msg"
                onEventMap(context.applicationContext, "upush_failure", map)
                Log.e("Upush","$name-$msg")
                if(name=="BANNER"){
                    setUpushBannerTime(context.applicationContext,0)
                }else{
                    setUpushNotificationTime(context.applicationContext,0)
                }
            }
        })
    }

    //请求通知栏广告的方法
    fun loadPushNotification(context: Context) {
        val time = getUpushNotificationTime(context.applicationContext)
        val load = if (time == 0L) {
            true
        } else {
            val s =(System.currentTimeMillis()/1000 - time)
            s>=10800
        }
        if (load) {
            UMUnionSdk.loadNotificationAd()
        }
    }



    //请求应用内浮窗广告的方法
    fun loadFloatingBanner(activity: Activity) {
        val time = getUpushBannerTime(activity.applicationContext)
        val load = if (time == 0L) {
            true
        } else {
            val s =(System.currentTimeMillis()/1000 - time)
            s>=120
        }
        if (load) {
            UMUnionSdk.loadFloatingBannerAd(activity)
        }
    }

    //设置关闭自动请求广告的方法
    fun setUpushAutoLoadEnable(isOpen: Boolean) {
        UMUnionSdk.setAdAutoLoadEnable(isOpen)
    }

    //广告的回调方法
    fun setCallback(callback: Callback) {
        this.callback = callback
        UMUnionSdk.setAdCallback(sAdCallback)
    }


    /**
     * 设置日志加密
     * 参数：boolean 默认为false（不加密）
     */
    fun setEncryptEnabled() {
        UMConfigure.setEncryptEnabled(true)
    }

    /**
     * 是否开启debug模式
     */
    fun setDebugLog(showLog: Boolean) {
        UMConfigure.setLogEnabled(showLog)
        debugLog = showLog
    }


    /**
     * 用于Fragment统计页面
     * pageName 是统计页面名称 自定义
     */
    fun onPageStart(pageName: String) {
        MobclickAgent.onPageStart(pageName)
    }

    /**
     * 用于Fragment统计页面
     * pageName 是统计页面名称 自定义
     */
    fun onPageEnd(pageName: String) {
        MobclickAgent.onPageEnd(pageName)
    }


    /**
     * 用于Fragment统计页面
     * pageName 是统计页面名称 自定义
     */
    fun onFragmentResume(context: Context, pageName: String) {
        MobclickAgent.onPageStart(pageName)
        MobclickAgent.onResume(context)
    }

    /**
     * 用于Fragment统计页面
     * pageName 是统计页面名称 自定义
     */
    fun onFragmentPause(context: Context, pageName: String) {
        MobclickAgent.onPageEnd(pageName)
        MobclickAgent.onPause(context)
    }


    /**
     * 用于Activity统计页面
     */
    fun onActivityResume(context: Context) {
        MobclickAgent.onResume(context)
    }

    /**
     * 用于Activity统计页面
     */
    fun onActivityPause(context: Context) {
        MobclickAgent.onPause(context)
    }

    /**
     * 用于单个值的统计
     */
    fun onEvent(context: Context, statisticsName: String) {
        MobclickAgent.onEvent(context, statisticsName)
        if (debugLog) Log.e(tag, "val:[$statisticsName]")
    }


    /**
     * 用于多个值的统计 map形式
     * 例:
     *  Map<String, String> map_value = new HashMap<String, String>();
     *  map_value.put("type", "popular");
     *  map_value.put("artist", "JJLin");
     *  MobclickAgent.onEventValue(this, "music", map_value, 12000);
     */
    fun onEventMap(context: Context, statisticsName: String, map: Map<String, String>) {
        MobclickAgent.onEvent(context, statisticsName, map)
        if (debugLog) {
            val buff = StringBuffer()
            for ((k, v) in map) {
                buff.append("[$k -> $v],")
            }
            Log.e(tag, "map:$statisticsName-$buff")
        }
    }

    /**
     * 对于好多应用，会在程序中杀死 进程，这样会导致我们统计不到此时Activity结束的信息，
     * 对于这种情况需要调用 'MobclickAgent.onKillProcess( Context )'
     * 方法，保存一些页面调用的数据。正常的应用是不需要调用此方法的。
     */
    fun onKillProcess(context: Context) {
        MobclickAgent.onKillProcess(context)
    }


    /**
     * 如果开发者自己捕获了错误，需要手动上传到【友盟+】服务器可以调用下面方法：
     */
    fun onReportError(e: Throwable, type: String) {
        UMCrash.generateCustomLog(e, type)
    }

    fun onReportError(e: String, type: String) {
        UMCrash.generateCustomLog(e, type)
    }


    /**
     *Upush时间拉取间隔
     */
    private fun getUpushNotificationTime(cxt: Context): Long {
        val prefs = cxt.getSharedPreferences("tools_config", Context.MODE_PRIVATE)
        return prefs.getLong("upush_notification_time", -1)
    }

    @SuppressLint("CommitPrefEdits")
    private fun setUpushNotificationTime(cxt: Context, time: Long) {
        val prefs = cxt.getSharedPreferences("tools_config", Context.MODE_PRIVATE)
        prefs.edit().putLong("upush_notification_time", time).apply()
    }


    /**
     *Upush时间拉取间隔
     */
    private fun getUpushBannerTime(cxt: Context): Long {
        val prefs = cxt.getSharedPreferences("tools_config", Context.MODE_PRIVATE)
        return prefs.getLong("upush_banner_time", -1)
    }

    @SuppressLint("CommitPrefEdits")
    private fun setUpushBannerTime(cxt: Context, time: Long) {
        val prefs = cxt.getSharedPreferences("tools_config", Context.MODE_PRIVATE)
        prefs.edit().putLong("upush_banner_time", time).apply()
    }
}
